# coding=utf-8
'''
Created on 2012-6-29

@author: wb_suoyao.shen
'''
import datetime
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
from ssyblog.tags.models import Tags
from ssyblog.diary.forms import TagForm

def addTags(request):
    nav_parent = 'Diary Manage'
    nav_child = 'Diary Tags Add'
    current_nav = 'tags_manage'
    return render_to_response('cms/diarys/tags_add.html', locals())

def queryTags(request,recommend = 'off'):
    tags_list = Tags.objects.tags_list(recommend = recommend)
    if recommend == 'off':
        nav_parent = 'Diary Manage'
        nav_child = 'Diary Tags Manage'
        current_nav = 'tags_manage'
        return render_to_response('cms/diarys/tags_query.html', locals())
    elif recommend == 'on':
        nav_parent = 'System Setting'
        nav_child = 'Recommend Tags'
        current_nav = 'recd_tags'
        return render_to_response('cms/diarys/recommend_tags.html', locals())

@csrf_exempt
def saveTags(request):
    if request.method == 'POST':
        form = TagForm(request.POST)
        if form.is_valid():
            obj = form.save(False)
            obj.write_time = datetime.datetime.now()
            obj.modify_time = datetime.datetime.now()
            obj.recommend = 'off'
            obj.save()
    else:
        form = TagForm()
    nav_parent = 'Diary Manage'
    nav_child = 'Diary Tags Add'
    current_nav = 'tags_manage'
    tips = 'create tag success'
    return render_to_response('cms/diarys/tags_add.html', locals())

def editTags(request,tagId,recommend):
    if tagId:
        tag = Tags.objects.get(pk=tagId)
    nav_parent = 'Diary Manage'
    nav_child = 'Diary Tags Edit'
    current_nav = 'tags_manage'
    return render_to_response('cms/diarys/tags_edit.html', locals())

@csrf_exempt
def updateTags(request,tagId,recommend):
    tag_to_update = get_object_or_404(Tags, pk = tagId)
    form = TagForm(request.POST, instance=tag_to_update)
    if form.is_valid():
        obj = form.save(False)
        obj.modify_time = datetime.datetime.now()
        obj.save()
    return queryTags(request,recommend)

def deleteTags(request,tagId,recommend):
    if tagId:
        Tags.objects.get(pk=tagId).delete()
    return queryTags(request,recommend)

def recommendTags(request,tagId,recommend):
    if tagId:
        tag = Tags.objects.get(pk=tagId)
        tag.recommend = recommend
        tag.save()
    if recommend == 'on':
        return queryTags(request,'off')
    elif recommend == 'off':
        return queryTags(request,'on')
